package com.southminority.ethnic.controller.admin.contact;

import com.southminority.ethnic.common.result.PageResult;
import com.southminority.ethnic.common.result.R;
import com.southminority.ethnic.service.contact.ContactService;
import com.southminority.ethnic.controller.contact.vo.ContactVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.ExampleObject;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 联系留言管理端控制器
 * 
 * @author SouthMinority
 */
@Slf4j
@Tag(name = "🛠️ 联系留言管理后台", description = "管理员管理用户联系留言的后台接口，包括查看、回复、删除等功能")
@RestController
@RequestMapping("/admin/contact")
@CrossOrigin
public class ContactAdminController {

    private final ContactService contactService;

    public ContactAdminController(ContactService contactService) {
        this.contactService = contactService;
    }

    /**
     * 分页查询联系留言列表
     */
    @GetMapping("/page")
    @Operation(
        summary = "分页查询联系留言列表", 
        description = "管理员分页查询用户提交的联系留言，支持按关键词、类型、状态筛选"
    )
    @ApiResponses({
        @ApiResponse(responseCode = "200", description = "查询成功",
            content = @Content(schema = @Schema(implementation = PageResult.class))),
        @ApiResponse(responseCode = "400", description = "请求参数错误"),
        @ApiResponse(responseCode = "401", description = "未登录或token无效"),
        @ApiResponse(responseCode = "403", description = "无管理员权限")
    })
    public R<PageResult<ContactVO>> getContactPage(
            @Parameter(description = "当前页码", example = "1") 
            @RequestParam(defaultValue = "1") Long current,
            @Parameter(description = "每页显示数量", example = "10") 
            @RequestParam(defaultValue = "10") Long size,
            @Parameter(description = "搜索关键词，支持姓名、邮箱、主题、内容搜索", example = "项目合作") 
            @RequestParam(required = false) String keyword,
            @Parameter(description = "联系类型筛选", example = "cooperation",
                schema = @Schema(allowableValues = {"consultation", "cooperation", "suggestion", "complaint", "research", "other"})) 
            @RequestParam(required = false) String contactType,
            @Parameter(description = "状态筛选", example = "0",
                schema = @Schema(allowableValues = {"0", "1", "2", "-1"})) 
            @RequestParam(required = false) Integer status) {
        try {
            PageResult<ContactVO> pageResult = contactService.getContactPage(current, size, keyword, contactType, status);
            return R.ok(pageResult);
        } catch (Exception e) {
            log.error("分页查询联系留言失败", e);
            return R.fail("查询失败: " + e.getMessage());
        }
    }

    /**
     * 获取所有联系留言列表
     */
    @GetMapping("/list")
    @Operation(
        summary = "获取所有联系留言列表", 
        description = "管理员获取所有联系留言的完整列表，不分页"
    )
    @ApiResponses({
        @ApiResponse(responseCode = "200", description = "获取成功",
            content = @Content(schema = @Schema(type = "array", implementation = ContactVO.class))),
        @ApiResponse(responseCode = "401", description = "未登录或token无效"),
        @ApiResponse(responseCode = "403", description = "无管理员权限")
    })
    public R<List<ContactVO>> getAllContactList() {
        try {
            List<ContactVO> contactList = contactService.getAllContactList();
            return R.ok(contactList);
        } catch (Exception e) {
            log.error("获取所有联系留言列表失败", e);
            return R.fail("获取列表失败: " + e.getMessage());
        }
    }

    /**
     * 根据ID获取联系留言详情
     */
    @GetMapping("/detail/{id}")
    @Operation(
        summary = "获取联系留言详情", 
        description = "管理员根据ID获取特定联系留言的详细信息"
    )
    @ApiResponses({
        @ApiResponse(responseCode = "200", description = "获取成功",
            content = @Content(schema = @Schema(implementation = ContactVO.class))),
        @ApiResponse(responseCode = "404", description = "联系留言不存在"),
        @ApiResponse(responseCode = "401", description = "未登录或token无效"),
        @ApiResponse(responseCode = "403", description = "无管理员权限")
    })
    public R<ContactVO> getContactById(
            @Parameter(description = "联系留言ID", example = "1", required = true) 
            @PathVariable Long id) {
        try {
            ContactVO contact = contactService.getContactById(id);
            return R.ok(contact);
        } catch (Exception e) {
            log.error("获取联系留言详情失败: id={}", id, e);
            return R.fail("获取详情失败: " + e.getMessage());
        }
    }

    /**
     * 更新联系留言状态
     */
    @PutMapping("/status/{id}")
    @Operation(
        summary = "更新联系留言状态", 
        description = "管理员更新联系留言的处理状态，如标记为已处理、已回复等"
    )
    @ApiResponses({
        @ApiResponse(responseCode = "200", description = "更新成功",
            content = @Content(schema = @Schema(implementation = Boolean.class))),
        @ApiResponse(responseCode = "404", description = "联系留言不存在"),
        @ApiResponse(responseCode = "400", description = "状态参数无效"),
        @ApiResponse(responseCode = "401", description = "未登录或token无效"),
        @ApiResponse(responseCode = "403", description = "无管理员权限")
    })
    public R<Boolean> updateContactStatus(
            @Parameter(description = "联系留言ID", example = "1", required = true) 
            @PathVariable Long id,
            @Parameter(description = "新状态：0-待处理，1-已处理，2-已回复，-1-已删除", example = "1", required = true,
                schema = @Schema(allowableValues = {"0", "1", "2", "-1"})) 
            @RequestParam Integer status) {
        try {
            log.info("管理员更新联系留言状态: ID={}, Status={}", id, status);
            Boolean result = contactService.updateContactStatus(id, status);
            return R.ok(result);
        } catch (Exception e) {
            log.error("更新联系留言状态失败: id={}, status={}", id, status, e);
            return R.fail("更新状态失败: " + e.getMessage());
        }
    }

    /**
     * 回复联系留言
     */
    @PutMapping("/reply/{id}")
    @Operation(
        summary = "回复联系留言", 
        description = "管理员回复用户的联系留言，支持通过URL参数传递回复内容"
    )
    @ApiResponses({
        @ApiResponse(responseCode = "200", description = "回复成功",
            content = @Content(schema = @Schema(implementation = Boolean.class))),
        @ApiResponse(responseCode = "404", description = "联系留言不存在"),
        @ApiResponse(responseCode = "400", description = "回复内容不能为空"),
        @ApiResponse(responseCode = "401", description = "未登录或token无效"),
        @ApiResponse(responseCode = "403", description = "无管理员权限")
    })
    public R<Boolean> replyContact(
            @Parameter(description = "联系留言ID", example = "1", required = true) 
            @PathVariable Long id,
            @Parameter(description = "回复内容", example = "感谢您的联系，我们会尽快与您沟通", required = true) 
            @RequestParam String replyContent,
            @Parameter(description = "回复人ID（可选，默认为当前登录管理员）", example = "1") 
            @RequestParam(required = false) Long replyUserId) {
        try {
            log.info("管理员回复联系留言: ID={}, ReplyUserId={}", id, replyUserId);
            // 如果没有提供replyUserId，可以从当前登录用户获取
            if (replyUserId == null) {
                replyUserId = 1L; // 默认管理员ID，实际应该从登录上下文获取
            }
            Boolean result = contactService.replyContact(id, replyContent, replyUserId);
            return R.ok(result);
        } catch (Exception e) {
            log.error("回复联系留言失败: id={}", id, e);
            return R.fail("回复失败: " + e.getMessage());
        }
    }

    /**
     * 回复联系留言（POST方式，支持复杂数据）
     */
    @PostMapping("/reply/{id}")
    @Operation(
        summary = "回复联系留言（POST方式）", 
        description = "管理员回复用户的联系留言，支持通过JSON传递回复内容，适用于复杂的回复数据"
    )
    @ApiResponses({
        @ApiResponse(responseCode = "200", description = "回复成功",
            content = @Content(schema = @Schema(implementation = Boolean.class))),
        @ApiResponse(responseCode = "404", description = "联系留言不存在"),
        @ApiResponse(responseCode = "400", description = "回复内容不能为空"),
        @ApiResponse(responseCode = "401", description = "未登录或token无效"),
        @ApiResponse(responseCode = "403", description = "无管理员权限")
    })
    public R<Boolean> replyContactPost(
            @Parameter(description = "联系留言ID", example = "1", required = true) 
            @PathVariable Long id,
            @io.swagger.v3.oas.annotations.parameters.RequestBody(
                description = "回复数据", 
                required = true,
                content = @Content(
                    mediaType = "application/json",
                    examples = @ExampleObject(
                        name = "回复数据示例",
                        value = """
                        {
                          "replyContent": "感谢您对我们实验室的关注，我们会尽快安排相关人员与您联系，详细讨论合作事宜。",
                          "replyUserId": 1
                        }
                        """
                    )
                )
            )
            @RequestBody Map<String, Object> replyData) {
        try {
            String replyContent = (String) replyData.get("replyContent");
            Long replyUserId = replyData.get("replyUserId") != null ? 
                              Long.valueOf(replyData.get("replyUserId").toString()) : 1L;
            
            log.info("管理员回复联系留言(POST): ID={}, ReplyUserId={}", id, replyUserId);
            Boolean result = contactService.replyContact(id, replyContent, replyUserId);
            return R.ok(result);
        } catch (Exception e) {
            log.error("回复联系留言失败: id={}", id, e);
            return R.fail("回复失败: " + e.getMessage());
        }
    }

    /**
     * 删除联系留言
     */
    @DeleteMapping("/delete/{id}")
    @Operation(
        summary = "删除联系留言", 
        description = "管理员软删除指定的联系留言，将状态标记为已删除"
    )
    @ApiResponses({
        @ApiResponse(responseCode = "200", description = "删除成功",
            content = @Content(schema = @Schema(implementation = Boolean.class))),
        @ApiResponse(responseCode = "404", description = "联系留言不存在"),
        @ApiResponse(responseCode = "401", description = "未登录或token无效"),
        @ApiResponse(responseCode = "403", description = "无管理员权限")
    })
    public R<Boolean> deleteContact(
            @Parameter(description = "联系留言ID", example = "1", required = true) 
            @PathVariable Long id) {
        try {
            log.info("管理员删除联系留言: ID={}", id);
            Boolean result = contactService.deleteContact(id);
            return R.ok(result);
        } catch (Exception e) {
            log.error("删除联系留言失败: id={}", id, e);
            return R.fail("删除失败: " + e.getMessage());
        }
    }

    /**
     * 批量删除联系留言
     */
    @DeleteMapping("/batch-delete")
    @Operation(
        summary = "批量删除联系留言", 
        description = "管理员批量软删除联系留言"
    )
    @ApiResponses({
        @ApiResponse(responseCode = "200", description = "批量删除成功",
            content = @Content(schema = @Schema(implementation = Boolean.class))),
        @ApiResponse(responseCode = "400", description = "ID列表不能为空"),
        @ApiResponse(responseCode = "401", description = "未登录或token无效"),
        @ApiResponse(responseCode = "403", description = "无管理员权限")
    })
    public R<Boolean> batchDeleteContact(
            @io.swagger.v3.oas.annotations.parameters.RequestBody(
                description = "要删除的联系留言ID列表",
                required = true,
                content = @Content(
                    mediaType = "application/json",
                    schema = @Schema(type = "array", implementation = Long.class),
                    examples = @ExampleObject(value = "[1, 2, 3]")
                )
            )
            @RequestBody List<Long> ids) {
        try {
            log.info("管理员批量删除联系留言: IDs={}", ids);
            Boolean result = contactService.batchDeleteContact(ids);
            return R.ok(result);
        } catch (Exception e) {
            log.error("批量删除联系留言失败", e);
            return R.fail("批量删除失败: " + e.getMessage());
        }
    }

    /**
     * 获取待处理留言数量
     */
    @GetMapping("/pending-count")
    @Operation(
        summary = "获取待处理留言数量", 
        description = "获取状态为“待处理”的联系留言总数，用于后台仪表盘提醒"
    )
    @ApiResponses({
        @ApiResponse(responseCode = "200", description = "获取成功",
            content = @Content(schema = @Schema(implementation = Long.class), examples = @ExampleObject(value = "15"))),
        @ApiResponse(responseCode = "401", description = "未登录或token无效"),
        @ApiResponse(responseCode = "403", description = "无管理员权限")
    })
    public R<Long> getPendingContactCount() {
        try {
            Long count = contactService.getPendingContactCount();
            return R.ok(count);
        } catch (Exception e) {
            log.error("获取待处理留言数量失败", e);
            return R.fail("获取数量失败: " + e.getMessage());
        }
    }

    /**
     * 获取最新留言列表
     */
    @GetMapping("/latest")
    @Operation(
        summary = "获取最新留言列表", 
        description = "获取最新提交的几条联系留言，用于后台首页快速预览"
    )
    @ApiResponses({
        @ApiResponse(responseCode = "200", description = "获取成功",
            content = @Content(schema = @Schema(type = "array", implementation = ContactVO.class))),
        @ApiResponse(responseCode = "401", description = "未登录或token无效"),
        @ApiResponse(responseCode = "403", description = "无管理员权限")
    })
    public R<List<ContactVO>> getLatestContactList(
            @Parameter(description = "要获取的留言数量限制", example = "5") 
            @RequestParam(defaultValue = "10") Integer limit) {
        try {
            List<ContactVO> contactList = contactService.getLatestContactList(limit);
            return R.ok(contactList);
        } catch (Exception e) {
            log.error("获取最新留言列表失败", e);
            return R.fail("获取列表失败: " + e.getMessage());
        }
    }

    /**
     * 获取联系类型统计
     */
    @GetMapping("/type-statistics")
    @Operation(
        summary = "获取联系类型统计", 
        description = "统计各种联系类型的数量，用于数据分析和图表展示"
    )
    @ApiResponses({
        @ApiResponse(responseCode = "200", description = "获取成功"),
        @ApiResponse(responseCode = "401", description = "未登录或token无效"),
        @ApiResponse(responseCode = "403", description = "无管理员权限")
    })
    public R<List<ContactVO>> getContactTypeStatistics() {
        try {
            List<ContactVO> statistics = contactService.getContactTypeStatistics();
            return R.ok(statistics);
        } catch (Exception e) {
            log.error("获取联系类型统计失败", e);
            return R.fail("获取统计失败: " + e.getMessage());
        }
    }

    /**
     * 测试接口
     */
    @GetMapping("/test")
    @Operation(summary = "测试接口连通性")
    @ApiResponse(responseCode = "200", description = "服务正常")
    public R<String> test() {
        return R.ok("联系留言管理后台服务正常");
    }
} 
